package com.hsy.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hsy.pojo.User;
import com.hsy.service.UserService;
import com.hsy.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@WebServlet("/EditUserServlet")
public class EditUserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8"); // 防止post请求乱码，设置请求的参数字符集为UTf-8
        response.setContentType("application/json;charset=UTF-8");  // // 设置响应头，指定返回数据的格式为JSON以及字符编码
        Long userId = Long.valueOf(request.getParameter("userId"));
        String userNumber = request.getParameter("userNumber");
        String userName = request.getParameter("userName");
        Long deptId = null;
        if(!request.getParameter("deptId").isEmpty()) { // 有可能前端不修改部门，所以需要加非空判断
            deptId = Long.valueOf(request.getParameter("deptId"));
        }
        String telephone = request.getParameter("telephone");
        String status = request.getParameter("status");
        User user = new User(userId, deptId, userNumber, userName,  telephone, status);
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> responseData = new HashMap<>();
        int result = userService.update(user);
        if (result > 0) {
            responseData.put("success", true);
            responseData.put("message", "修改成功");
        }else {
            responseData.put("success", false);
            responseData.put("message", "修改失败");
        }
        // 将响应数据转换为JSON字符串
        String responseJson = objectMapper.writeValueAsString(responseData);
        // 通过PrintWriter将JSON格式的响应数据写回给前端
        PrintWriter writer = response.getWriter();
        writer.write(responseJson);
        writer.flush();
        writer.close();
    }
}
